<template>
  <div class="authColumnConfig">
    <el-dialog
      :title="title"
      :visible.sync="showDialog"
      :before-close="handleClose"
      :close-on-click-modal:="closeOnClickModal"
      append-to-body
      width="90%"
    >
      <el-row ref="authConfig" class="authConfig">
        <el-col :span="8" class="tableColumns">
          <el-table
            :data="columns"
            border
            highlight-current-row
            @current-change="handleCurrentChange"
          >
            <el-table-column prop="label" label="列名" align="center">
            </el-table-column>
            <el-table-column
              prop="displayName"
              label="别名"
              align="center"
              min-width="130"
            >
              <template slot-scope="{ row }">
                <span v-show="!row.edit">{{ row["displayName"] || "无" }}</span>
                <el-input
                  v-show="row.edit"
                  v-model="row.displayName"
                  placeholder="请输入别名"
                  clearable
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="{ row, $index }">
                <el-button
                  v-show="!row.edit"
                  @click="handleEdit($index, row)"
                  type="text"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  v-show="row.edit"
                  @click="saveDisplayName($index, row)"
                  type="text"
                  size="small"
                  >保存</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="16">
          <el-transfer
            v-model="checkedRoles"
            :props="{
              key: 'roleCodg',
              label: 'roleName'
            }"
            filterable
            :titles="['全部的角色', '赋权限角色']"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}'
            }"
            :data="busiRoles"
            @change="handleChange"
          >
          </el-transfer>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose()" size="medium">取 消</el-button>
        <el-button type="primary" @click="save()" size="medium"
          >确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Message from "../../utils/Messager";
import _ from "lodash";
// import api from "@api/base/base-api";

export default {
  props: {
    show: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
    source: {
      type: String,
      default: () => {
        return {};
      }
    },
    optionsColumns: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      showDialog: false,
      title: "表格权限控制",
      closeOnClickModal: true,
      checkedRoles: [],
      busiRoles: [],
      columns: [],
      showEdit: [],
      showBtn: [],
      submitCondition: [],
      rowChecked: {},
      rolesChecked: []
    };
  },
  watch: {
    show(newValue) {
      this.showDialog = newValue;
      if (newValue) {
        this.init();
      }
    }
  },
  methods: {
    async init() {
      await this.getAllBusiRoles();
      await this.getGridAuthRelation();
      this.setTableData();
    },
    async getAllBusiRoles() {
      // const result = await api.getAllBusiRoles(this.tableData);
      if (result.code == 0) {
        this.busiRoles = result.data.data;
      } else {
        Message.error({ message: result.message });
      }
    },
    async getGridAuthRelation() {
      this.submitCondition = _.cloneDeep(
        await this.$utils.TableColumnControl.getTableAuthConfig(this.source)
      );
    },
    setTableData() {
      this.columns = _.cloneDeep(this.optionsColumns);
      for (let item of this.columns) {
        const prop = item.prop;
        item["edit"] = false;
        const column = this.submitCondition.find(value => {
          return value.prop == prop;
        });
        if (column && column.label) {
          item["displayName"] = column.label;
        }
      }
    },
    handleChange(checkedArray) {
      if (checkedArray && this.rowChecked) {
        //修改
        const index = this.checkRelation();
        if (index > -1) {
          this.submitCondition.splice(index, 1);
        }
        const item = {
          gridId: this.source,
          prop: this.rowChecked.prop,
          label: this.rowChecked.displayName,
          roles: checkedArray
        };
        this.submitCondition.push(item);
      }
      // console.log(this.submitCondition);
    },
    checkRelation() {
      if (this.submitCondition.length > 0) {
        const prop = this.rowChecked.prop;
        const index = this.submitCondition.findIndex(value => {
          return value.prop == prop;
        });
        return index;
      } else {
        return -1;
      }
    },
    handleCurrentChange(val) {
      this.rowChecked = val;
      const index = this.checkRelation();
      this.checkedRoles = index > -1 ? this.submitCondition[index].roles : [];
    },
    async save() {
      // const result = await api.saveGridAuthRelation(this.submitCondition);
      if (result.code == 0) {
        Message.ok({ message: "保存权限成功" });
      } else {
        Message.error({ message: result.message });
      }
    },
    handleEdit(index) {
      let column = this.columns[index];
      column.edit = true;
      this.$set(this.columns, index, column);
    },
    async saveDisplayName(index, row) {
      const param = {
        gridId: this.source,
        prop: row.prop,
        label: row.displayName
      };
      const result = await api.saveGridDisplayName(param);
      if (result.code == 0) {
        let column = this.columns[index];
        column.edit = false;
        this.$set(this.columns, index, column);
        //角色表更新
        Message.ok({ message: "保存别名成功" });
      } else {
        Message.error({ message: result.message });
      }
    },
    handleClose() {
      this.$emit("close");
    }
  }
};
</script>
<style lang="scss" scoped>
.authConfig {
  height: 100%;
}

.tableColumns {
  padding: 0 15px;
  overflow-y: auto;
}

::v-deep .el-button + .el-button {
  margin-left: 10px;
}

::v-deep .el-transfer__buttons {
  display: inline-block;
  vertical-align: middle;
  padding: 0 10px;
}
</style>
